package com.xiaoruyuan.firstday.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.xiaoruyuan.firstday.domain.exception.BusinessException;
import com.xiaoruyuan.firstday.domain.exception.MemberExceptionEnum;
import com.xiaoruyuan.firstday.domain.vo.MemberVo;
import com.xiaoruyuan.firstday.domain.web.BaseResponse;
import com.xiaoruyuan.firstday.domain.web.RequestData;
import com.xiaoruyuan.firstday.service.MemberService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhengqiang
 * @version 1.0
 * @Date 2021/8/3 14:08
 * @Description 会员控制器
 */
@RestController
public class MemberController extends BaseController {
    /**
     * 请求参数中，昵称的key
     */
    public static final String REQUEST_NICKNAME_KEY = "nickname";

    /**
     * 查看会员信息
     *
     * @param phone 手机号
     * @return
     */
    @PostMapping("/client/member/info")
    public BaseResponse info(@RequestHeader String phone) {
        try {
            MemberService memberService = new MemberService();
            MemberVo memberVo = memberService.findMemberInfoByMobile(phone);
            System.out.println(String.format("用户脱敏手机号：%s",memberVo.getMobile()));
            System.out.println(String.format("用户ID：%d",memberVo.getUid()));
            System.out.println(String.format("用户昵称：%s",memberVo.getNickname()));
            return BaseResponse.success(memberVo);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.error();
        }
    }

    /**
     * 修改会员昵称
     *
     * @param phone 手机号
     * @param requestData 请求数据
     * @return
     */
    @PostMapping("/client/member/updateNickname")
    public BaseResponse updateNickname(@RequestHeader String phone, RequestData requestData) {
        try {
            String newNickName = getNewNickName(requestData);
            System.out.println("newNickName:" + newNickName);
            MemberService memberService = new MemberService();
            memberService.updateNicknameByMobile(phone, newNickName);
            return BaseResponse.success("修改成功");
        } catch (BusinessException e) {
            return BaseResponse.error(e.getMessage(), e.getCode());
        } catch (Exception e) {
            return BaseResponse.error();
        }
    }


    /**
     * 获取新的昵称
     *
     * @param requestData 请求数据
     * @return
     */
    private String getNewNickName(RequestData requestData) {
        JSONObject dataJsonObject = getDataJsonObject(requestData);
        return dataJsonObject.getString(REQUEST_NICKNAME_KEY);
    }



}
